package com.demo.task.ui

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.demo.task.bean.PlanBean
import com.demo.task.ext.bind
import com.demo.task.ext.getSerial
import com.demo.task.ext.getVersion
import com.demo.task.service.ConfigService
import com.demo.task.service.ConfigService.Companion.startConfigService
import com.demo.task.service.UpdateService.Companion.startUpdateService
import com.demo.task.socket.RemoteInterface
import com.demo.task.ui.screen.SyncScreen
import com.demo.task.ui.screen.Window
import com.demo.task.ui.widget.DisplaySystemTime
import com.demo.task.utils.DownloadUtil
import com.demo.task.utils.WebViewUtils
import com.demo.task.vm.MainViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    companion object {
        const val TAG = "MainActivity"
    }

    @Inject
    lateinit var socketIO: RemoteInterface

    @Inject
    lateinit var downloadUtil: DownloadUtil

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        startUpdateService()
        WebViewUtils.hookWebView()
        setContent {
            val viewModel = viewModel<MainViewModel>()

            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black)
            ) {
                Player(viewModel, socketIO)
                Information(viewModel, socketIO, downloadUtil)
            }
        }

        socketIO.connect()
    }


    override fun onDestroy() {
        super.onDestroy()
        socketIO.close()
        downloadUtil.clearAll()
    }
}


@Composable
private fun Player(viewModel: MainViewModel, socketIO: RemoteInterface) {
    Box {
        val boxList by viewModel.box.collectAsState()
        if (boxList.isNotEmpty()) {
            //窗口
            if (viewModel.isSameMedia) {
                SyncScreen(boxList, viewModel, socketIO)
            } else {
                WindowPlayer(viewModel, socketIO)
            }
        }
    }

}

@Composable
private fun Information(
    viewModel: MainViewModel,
    remote: RemoteInterface,
    downloadUtil: DownloadUtil
) {
    Row {
        State(remote, viewModel)
        Column(Modifier.padding(top = 6.dp)) {
            DownInfo(downloadUtil)//下载信息
            UpdateInfo()//更新信息
            DeviceInfo(viewModel)//设备和交通信息
        }
    }
}

@Composable
private fun UpdateInfo() {
    Box {
        val context = LocalContext.current
        var updating by remember { mutableStateOf("") }

        LaunchedEffect(Unit) {
            //更新进度
            launch {
                context.bind<ConfigService>()?.updating?.collectLatest {
                    updating = it
                }
            }
        }

        if (updating.isNotEmpty()) {
            Text(
                text = updating,
                fontSize = 10.sp,
                color = Color.White
            )
        }
    }
}

@Composable
private fun DownInfo(downloadUtil: DownloadUtil) {
    Box {
        val downInfo by downloadUtil.downProgress.collectAsStateWithLifecycle("")
        if (downInfo.isNotEmpty()) {
            Text(
                text = downInfo,
                fontSize = 10.sp,
                color = Color.White
            )
        }
    }
}

@Composable
private fun DeviceInfo(viewModel: MainViewModel) {
    Column {
        val context = LocalContext.current
        val planBean by viewModel.planBean.collectAsStateWithLifecycle()

        planBean?.also { plan ->
            Log.w("TAG", "Information: $plan")
            //触发配置服务
            context.startConfigService(plan)

            //交通
            if (plan.trafficSync == 1 && !plan.trafficInfo.isNullOrEmpty()) {
                plan.trafficInfo?.firstOrNull()?.also { trafficInfos ->
                    TrafficInfo(plan, trafficInfos)
                }
            }

            //天气
            if (plan.weatherSync == 1 && !plan.weatherInfo.isNullOrEmpty()) {
                val weatherInfo = plan.weatherInfo.first()
                WeatherInfo(weatherInfo)
            }

            //sn信息
            if (plan.snShow == 1) {
                Row {
                    Text(
                        text = getSerial(),
                        color = Color.White,
                        fontSize = 10.sp
                    )
                    Text(
                        text = getVersion(),
                        color = Color.White,
                        modifier = Modifier.padding(start = 4.dp),
                        fontSize = 10.sp
                    )
                }
            }

            //时间
            if (plan.timeShow == 1) {
                Box {
                    DisplaySystemTime()
                }
            }
        }
    }
}

@Composable
private fun State(socketIO: RemoteInterface, viewModel: MainViewModel) {
    Box(Modifier.padding(6.dp)) {
        val isConnect by socketIO.isConnect.collectAsState()
        val planBean by viewModel.planBean.collectAsState()

        if (planBean?.signalShow == 1) {
            Canvas(Modifier.size(6.dp)) {
                drawCircle(
                    color = if (isConnect) Color.Green else Color.Red,
                    radius = size.width / 2,
                )
            }
        }
    }
}

@Composable
private fun WindowPlayer(
    viewModel: MainViewModel,
    socketIO: RemoteInterface,
) {
    Box {
        val boxList by viewModel.box.collectAsStateWithLifecycle(emptyList())

        boxList.forEachIndexed { index, box ->
            key(box.uid) {
                box.flag = index == 1
                Window(
                    viewModel,
                    socketIO,
                    box
                )
            }
        }
    }
}


@Composable
private fun TrafficInfo(
    planBean: PlanBean,
    trafficInfo: PlanBean.TrafficInfo
) {
    Row {
        val sb = StringBuilder()
        if (planBean.area?.isNotEmpty() == true) {
            sb.append(planBean.area)
            sb.append("\t")
        }
        sb.append("交通:${trafficInfo.evaluation.description}")
        Text(
            text = sb.toString(),
            color = Color.White,
            fontSize = 10.sp,
        )
    }
}

@Composable
fun WeatherInfo(
    weatherInfo: PlanBean.WeatherInfo
) {
    Row {
        Text(
            text = "温度:${weatherInfo.temperature}°",
            color = Color.White,
            fontSize = 10.sp
        )
        Text(
            text = "湿度:${weatherInfo.humidity}%",
            color = Color.White,
            fontSize = 10.sp,
            modifier = Modifier.padding(start = 10.dp)
        )
    }
}


